package com.lanlian.cayman.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.R;
import com.lanlian.cayman.activity.KLineActivity;
import com.lanlian.cayman.activity.ProfitLossActivity;
import com.lanlian.cayman.adapter.TradePositionAdapter;
import com.lanlian.cayman.dialog.TradeConfirmDialog;
import com.lanlian.cayman.proto.ProtoManager;
import com.lanlian.cayman.socket.MySocketManager;
import com.lanlian.cayman.socket.SocketCallImpl;
import com.lanlian.cayman.utils.NumberManager;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.commonlib.base.BaseLazyFragment;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.PositionDetailsInfo;
import com.lanlian.commonlib.bean.ReqPositionDetails;
import com.lanlian.commonlib.bean.RespPositionDetails;
import com.lanlian.commonlib.dao.DBManager;
import com.lanlian.commonlib.data.GoodsBean;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.commonlib.util.OnEventID;
import com.lanlian.commonlib.util.OnEventUtils;
import com.lanlian.uikit.ActionItem;
import com.lanlian.uikit.CustomBottomSheetDialog;
import com.lanlian.utillib.CommonUtils;
import com.lanlian.utillib.NumberUtils;
import com.oms.rpc.protobuf.FuturesTradeInfo;
import com.oms.rpc.protobuf.FuturesTradeReq;
import com.oms.rpc.protobuf.FuturesTradeResp;
import com.oms.rpc.protobuf.OMSTradeReq;
import com.oms.rpc.protobuf.OMSTradeRsp;
import com.oms.rpc.protobuf.RequestInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.math.BigDecimal;
import java.util.ArrayList;

import static java.math.BigDecimal.ROUND_HALF_UP;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/14 16:51
 *     desc   : 交易-持仓TAB
 *     version: 1.0
 * </pre>
 */
public class TradePositionFragment extends BaseLazyFragment {

    private RecyclerView mRecycleView;
    private SmartRefreshLayout mLayRefresh;

    public ArrayList<PositionDetailsInfo> mList = new ArrayList<>();
    private TradePositionAdapter mAdapter;

    private boolean mIsFirst = true;
    private long time;

    private TradeConfirmDialog mTradeConfirmDialog;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (!mIsFirst && isVisibleToUser) {
            mLayRefresh.autoRefresh();
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trade_position, null);
        initView(view);
        setListeners();
        initAdapter();
        return view;
    }

    @Override
    protected void loadData() {
        mIsFirst = false;
        mLayRefresh.autoRefresh(500);
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mRecycleView = view.findViewById(R.id.recycle_view);
        mLayRefresh = view.findViewById(R.id.lay_refresh);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mLayRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                getPositionDetails();
            }
        });
    }

    /**
     * 初始化Adapter
     */
    private void initAdapter() {
        mAdapter = new TradePositionAdapter(R.layout.adapter_trade_position, mList);
        mRecycleView.setAdapter(mAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecycleView.setLayoutManager(linearLayoutManager);
        mAdapter.bindToRecyclerView(mRecycleView);
        mRecycleView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int mPosition) {
                CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(getActivity(), "请选择");
                dialog.addAction(new ActionItem("平仓"));
                dialog.addAction(new ActionItem("K线图"));
                dialog.addAction(new ActionItem("止盈止损"));
                dialog.addAction(new ActionItem("市价反手", R.color.color_T7));
                dialog.setOnItemClickListener(new CustomBottomSheetDialog.OnItemOnClickListener() {
                    @Override
                    public void onItemClick(ActionItem item, int position) {
                        if (isFastClick() || CommonUtils.isListEmpty(mList)) {
                            return;
                        }
                        switch (item.mTitle) {
                            case "平仓":
                                OnEventUtils.onEvent(getActivity(), OnEventID.CLEAR_POSITION);
                                pingCang(mList.get(mPosition));
                                break;
                            case "K线图":
                                startActivity(new Intent(getActivity(), KLineActivity.class)
                                        .putExtra("name", mList.get(mPosition).getContractName())
                                        .putExtra("id", mList.get(mPosition).getVcContractCode()));
                                break;
                            case "止盈止损":
                                startActivity(new Intent(getActivity(), ProfitLossActivity.class)
                                        .putExtra("positionDetailsInfo", mList.get(mPosition)));
                                break;
                            case "市价反手":
                                if (!mDBManager.getSecondConfirm()) {
                                    priceReverse(mList.get(mPosition));
                                } else {
                                    PositionDetailsInfo positionDetailsInfo = mList.get(mPosition);
                                    mTradeConfirmDialog = new TradeConfirmDialog(getActivity());
                                    mTradeConfirmDialog.setText(positionDetailsInfo.getContractName() + "，价格：市价，反手：" +
                                            positionDetailsInfo.getlCurrentAmount() + "手");
                                    mTradeConfirmDialog.setOnOk(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            priceReverse(mList.get(mPosition));
                                        }
                                    });
                                    mTradeConfirmDialog.showDialog();
                                }
                                break;
                            default:
                                break;
                        }
                    }
                });
                dialog.showDialog();
            }
        });
    }

    /**
     * 获取持仓信息
     */
    private void getPositionDetails() {
        VolleyRequestUtils.getInstance().getPositionDetails(this.toString(), new ReqPositionDetails(),
                new INetWorkCallback() {
                    @Override
                    public void onSuccess(Object response) {
                        time = System.currentTimeMillis();
                        mLayRefresh.finishRefresh();
                        RespPositionDetails respPositionDetails = (RespPositionDetails) response;
                        mList = respPositionDetails.getDataList();
                        mAdapter.setNewData(mList);
                        calculationPnl();
                    }

                    @Override
                    public void onFail(BaseResponse baseResponse) {
                        mLayRefresh.finishRefresh();
                        showToast(baseResponse.getMsg());
                    }
                });
    }

    /**
     * 市价反手
     */
    private void priceReverse(PositionDetailsInfo p) {
        showLoadingDialog();
        OMSTradeReq.Builder builderOms = OMSTradeReq.newBuilder();
        ProtoManager pm = new ProtoManager();
        RequestInfo.Builder builder = pm.getInitRequestInfo();
        builder.setLRequreId(6000);
        builderOms.setRequestInfo(builder);
        FuturesTradeInfo.Builder fb;
        FuturesTradeReq.Builder builder_fr = FuturesTradeReq.newBuilder();
        builderOms.setRequestInfo(builder);
        fb = pm.getInitFuturesTradeInfo();
        fb.setVcFuturesCode(p.getVcContractCode());
        fb.setLOrderAmount(p.getlCurrentAmount() * 2);
        fb.setEnOrderPrice(0);
        fb.setCPriceType("1");
        if ("1".equals(p.getcPositionFlag())) {
            fb.setCOrderDirection("2");
        } else {
            fb.setCOrderDirection("1");
        }
        fb.setLPositionNo(p.getlPositionNo().intValue());
        builder_fr.addFuturestradeinfo(fb);
        builderOms.setFuturestradeReq(builder_fr);
        OMSTradeReq om = builderOms.build();

        SocketCallImpl sc = new SocketCallImpl(this) {
            @Override
            public void message(byte[] data) {
                try {
                    dismissLoadingDialog();
                    if (mTradeConfirmDialog != null) {
                        mTradeConfirmDialog.dismiss();
                    }
                    OMSTradeRsp oms = OMSTradeRsp.parseFrom(data);
                    if (oms.getRequestStatus() == 0) {
                        FuturesTradeResp fr = oms.getFuturestradeResp();
                        if (fr.getErrcode() == 0) {
                            showToast("下单成功");
                            EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                            EventBusUtils.post(new EventMessage(EventCode.EVENT_ENTRUST_REFRESH));
                            EventBusUtils.post(new EventMessage(EventCode.EVENT_POSITION_REFRESH));
                        } else {
                            showToast(fr.getErrmsg());
                        }
                    } else if (oms.getRequestStatus() == 2) {
                        showToast("登录过期");
                        DBManager.getInstance().setLoginOut();
                        EventBusUtils.post(new EventMessage(EventCode.EVENT_LOGIN_OUT_REFRESH));
                        EventBusUtils.post(new EventMessage(EventCode.EVENT_FUCK_OUT_REFRESH));
                    } else {
                        showToast(oms.getStatusInfo());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        MySocketManager ms = new MySocketManager();
        ms.sendData(om.toByteArray(), sc);
    }

    /**
     * 全部平仓
     */
    public void pingCangAll() {
        OMSTradeReq.Builder builder_oms = OMSTradeReq.newBuilder();
        ProtoManager pm = new ProtoManager();
        RequestInfo.Builder builder = pm.getInitRequestInfo();
        builder.setLRequreId(6000);
        builder_oms.setRequestInfo(builder);
        FuturesTradeInfo.Builder fb;
        FuturesTradeReq.Builder builder_fr = FuturesTradeReq.newBuilder();
        PositionDetailsInfo p1 = null;

        for (int i = 0; i < mList.size(); i++) {
            p1 = mList.get(i);
            fb = pm.getInitFuturesTradeInfo();
            fb.setVcFuturesCode(p1.getVcContractCode());
            fb.setLOrderAmount(p1.getlCurrentAmount() - p1.getlPresaleAmount());
            fb.setEnOrderPrice(0);
            fb.setCPriceType("1");
            if ("1".equals(p1.getcPositionFlag())) {
                fb.setCOrderDirection("2");
            } else if ("2".equals(p1.getcPositionFlag())) {
                fb.setCOrderDirection("1");
            }
            fb.setLOrderType(8);
            fb.setLPositionNo(p1.getlPositionNo().intValue());
            builder_fr.addFuturestradeinfo(fb);
            builder_oms.setFuturestradeReq(builder_fr);
        }
        OMSTradeReq om = builder_oms.build();

        showLoadingDialog();
        SocketCallImpl sc = new SocketCallImpl(this) {
            @Override
            public void message(byte[] data) {
                dismissLoadingDialog();
                try {
                    if (mTradeConfirmDialog != null) {
                        mTradeConfirmDialog.dismiss();
                    }
                    OMSTradeRsp oms = OMSTradeRsp.parseFrom(data);
                    if (oms.getRequestStatus() == 0) {
                        FuturesTradeResp fr = oms.getFuturestradeResp();
                        if (fr.getErrcode() == 0) {
                            showToast("委托请求成功！");
                        } else {
                            showToast(fr.getErrmsg());
                        }
                        EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                        EventBusUtils.post(new EventMessage(EventCode.EVENT_ENTRUST_REFRESH));
                        EventBusUtils.post(new EventMessage(EventCode.EVENT_POSITION_REFRESH));
                    } else if (oms.getRequestStatus() == 2) {
                        showToast("登录过期");
                        DBManager.getInstance().setLoginOut();
                        EventBusUtils.post(new EventMessage(EventCode.EVENT_LOGIN_OUT_REFRESH));
                        EventBusUtils.post(new EventMessage(EventCode.EVENT_FUCK_OUT_REFRESH));
                    } else {
                        showToast(oms.getStatusInfo());
                        if (mTradeConfirmDialog != null) {
                            mTradeConfirmDialog.dismiss();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (mTradeConfirmDialog != null) {
                        mTradeConfirmDialog.dismiss();
                    }
                }
            }
        };
        MySocketManager ms = new MySocketManager();
        ms.sendData(om.toByteArray(), sc);
    }

    /**
     * 平仓
     */
    private void pingCang(PositionDetailsInfo positionDetailsInfo) {
        if (positionDetailsInfo.getlCurrentAmount() - positionDetailsInfo.getlPresaleAmount() <= 0) {
            showToast(String.format("持仓已有委托，请先撤单", positionDetailsInfo.getVcContractCode()));
            return;
        }
        Intent intent = new Intent(getContext(), KLineActivity.class);
        intent.putExtra("id", positionDetailsInfo.getVcContractCode());
        intent.putExtra("name", positionDetailsInfo.getContractName());
        intent.putExtra("pi", positionDetailsInfo);
        getActivity().startActivity(intent);
    }

    /**
     * 计算本币盈亏（tick推送盈亏）
     */
    private void calculationPnl(HqMsg.YsHqInfo ysHqInfo) {
        for (PositionDetailsInfo positionDetailsInfo : mList) {
            if (positionDetailsInfo.getVcContractCode().equals(ysHqInfo.getCommodityNo() + ysHqInfo.getContractNo1())) {
                PositionDetailsInfo position = LLApplication.getPositionList().get(mList.indexOf(positionDetailsInfo));
                positionDetailsInfo.setCurrentPrice(position.getCurrentPrice());
                positionDetailsInfo.setJj(position.getJj());
                positionDetailsInfo.setAveragePrice(position.getAveragePrice());
                positionDetailsInfo.setProfitLoss(position.getProfitLoss());
                mAdapter.notifyItemChanged(mList.indexOf(positionDetailsInfo), 1);
                break;
            }
        }
    }

    /**
     * 计算初始盈亏
     */
    private void calculationPnl() {
        for (PositionDetailsInfo positionDetailsInfo : mList) {
            GoodsBean goodsBean = MarketFragment.getRespMarket().getGoods(positionDetailsInfo.getVcContractCode());
            if (goodsBean == null) {
                continue;
            }
            int count = NumberManager.getNumberDecimalDigits(goodsBean.minChange);
            String currentPrice = NumberUtils.roundStr(positionDetailsInfo.getPrice(), count, ROUND_HALF_UP);
            positionDetailsInfo.setCurrentPrice(currentPrice);
            int flag = "1".equals(positionDetailsInfo.getcPositionFlag()) ? 1 : -1;
            double averagePrice = positionDetailsInfo.getEnTotalValue() / Double.parseDouble(goodsBean.contractMultiplier)
                    / positionDetailsInfo.getlCurrentAmount();
            positionDetailsInfo.setJj(averagePrice);
            double pnl = NumberUtils.sub(currentPrice, String.valueOf(averagePrice))
                    / Double.parseDouble(goodsBean.minChange) * Double.parseDouble(goodsBean.priceUnit) * flag * positionDetailsInfo.getlCurrentAmount();
            positionDetailsInfo.setProfitLoss(NumberUtils.round(pnl, 2, BigDecimal.ROUND_HALF_DOWN));
            mAdapter.notifyItemChanged(mList.indexOf(positionDetailsInfo), 1);
        }
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_POSITION_REFRESH:
            case EventCode.EVENT_LOGIN_REFRESH:
                getPositionDetails();
                break;
            case EventCode.EVENT_MARKET:
                HqMsg.YsHqInfo ysHqInfo = (HqMsg.YsHqInfo) event.getData();
                calculationPnl(ysHqInfo);
                break;
            case EventCode.EVENT_MARKET_COLOR_CHANGE:
                mAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

}
